package com.example.wordmemory;

import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.wordmemory.entity.Word;
import com.example.wordmemory.utils.WordDBHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;

public class WordLearning extends AppCompatActivity {
    private WordDBHelper dbHelper;
    private ArrayList<Word> wordList = new ArrayList<>();
    private int currentIndex = 0;
    private boolean isReviewMode = false;

    // UI
    private TextView tvWord, tvPhonetic, tvExample, tvProgress, viewMask, btnKnown, btnUnknown, btnPrevious;
    private View ivStar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_word_learning);

        dbHelper = new WordDBHelper(this);

        // 1. 绑定控件
        tvWord = findViewById(R.id.tv_word);
//        tvPhonetic = findViewById(R.id.tv_phonetic);
        tvExample = findViewById(R.id.tv_example);
        tvProgress = findViewById(R.id.tv_progress);
        viewMask = findViewById(R.id.view_mask);
        btnKnown = findViewById(R.id.btn_known);
        btnUnknown = findViewById(R.id.btn_unknown);
        btnPrevious = findViewById(R.id.btn_previous);
        ivStar = findViewById(R.id.iv_star);

        // 2. 判断模式
        String mode = getIntent().getStringExtra("mode");
        isReviewMode = "review".equals(mode);

        // 3. 加载单词
        loadWords();

        // 4. 显示第一个单词
        showWord();

        // 5. 按钮事件
        btnKnown.setOnClickListener(v -> onAnswer(true));
        btnUnknown.setOnClickListener(v -> onAnswer(false));
        btnPrevious.setOnClickListener(v -> {
            if (currentIndex > 0) {
                currentIndex--;
                showWord();
            }
        });
    }

    private void loadWords() {
        wordList.clear();
        if (isReviewMode) {
            // 复习模式：只加载今天应复习的单词
            java.util.List<Integer> reviewIds = dbHelper.getTodayReviewWords();
            if (!reviewIds.isEmpty()) {
                StringBuilder sb = new StringBuilder();
                sb.append("?");
                for (int i = 1; i < reviewIds.size(); i++) sb.append(",?");
                String sql = "SELECT * FROM words WHERE id IN (" + sb + ")";
                String[] args = new String[reviewIds.size()];
                for (int i = 0; i < reviewIds.size(); i++) args[i] = String.valueOf(reviewIds.get(i));
                Cursor c = dbHelper.getReadableDatabase().rawQuery(sql, args);
                while (c.moveToNext()) {
                    wordList.add(cursorToWord(c));
                }
                c.close();
            }
        } else {
            // 学习模式：只加载未学过的单词，最多20个
            Cursor c = dbHelper.getReadableDatabase().rawQuery(
                "SELECT * FROM words WHERE id NOT IN (SELECT word_id FROM study) ORDER BY id ASC LIMIT 20", null);
            while (c.moveToNext()) {
                wordList.add(cursorToWord(c));
            }
            c.close();
        }
        currentIndex = 0;
    }

    private Word cursorToWord(Cursor c) {
        Word w = new Word();
        w.id = c.getInt(c.getColumnIndexOrThrow("id"));
        w.word = c.getString(c.getColumnIndexOrThrow("word"));
        w.meaning = c.getString(c.getColumnIndexOrThrow("meaning"));
        w.example = c.getString(c.getColumnIndexOrThrow("example"));
        w.modifyTime = c.getString(c.getColumnIndexOrThrow("modify_time"));
        return w;
    }

    private void showWord() {
        if (wordList.isEmpty()) {
            Toast.makeText(this, "没有可学习/复习的单词", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        Word w = wordList.get(currentIndex);
        tvWord.setText(w.word);
        // tvPhonetic.setText(w.phonetic); // 如有音标字段可补充
        tvExample.setText(w.example);
        tvProgress.setText((currentIndex + 1) + "/" + wordList.size());
        viewMask.setText("******"); // 遮挡释义
        // 复习模式下根据is_memorized设置星星颜色
        if (isReviewMode) {
            int isMemorized = getIsMemorized(w.id);
            if (ivStar instanceof android.widget.ImageView) {
                if (isMemorized == 1) {
                    ((android.widget.ImageView) ivStar).setColorFilter(0xFFFFD600); // 明黄色
                } else {
                    ((android.widget.ImageView) ivStar).setColorFilter(0xFFCCCCCC); // 灰色
                }
            }
        } else {
            if (ivStar instanceof android.widget.ImageView) {
                ((android.widget.ImageView) ivStar).setColorFilter(0xFFCCCCCC); // 学习模式默认灰色
            }
        }
    }

    // 获取当前单词的is_memorized字段
    private int getIsMemorized(int wordId) {
        int result = 0;
        Cursor c = dbHelper.getReadableDatabase().rawQuery(
            "SELECT is_memorized FROM study WHERE word_id=? ORDER BY review_time DESC LIMIT 1",
            new String[]{String.valueOf(wordId)});
        if (c.moveToFirst()) {
            result = c.getInt(0);
        }
        c.close();
        return result;
    }

    private void onAnswer(boolean known) {
        Word w = wordList.get(currentIndex);
        if (isReviewMode) {
            // 复习：只更新已有记录，复习后立即更新review_time
            dbHelper.updateStudyForReview(w.id, known);
        } else {
            // 学习：只插入未学过的单词，插入前先查是否已存在
            dbHelper.insertOrUpdateStudyForLearn(w.id, known);
        }
        // 显示释义
        viewMask.setText(w.meaning);

        // 自动跳到下一个
        viewMask.postDelayed(() -> {
            if (currentIndex < wordList.size() - 1) {
                currentIndex++;
                showWord();
            } else {
                Toast.makeText(this, "本轮已完成", Toast.LENGTH_SHORT).show();
                // 统计并累计更新calendar表
                String today = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new java.util.Date());
                
                // 确保calendar表有今天的记录
                Cursor c = dbHelper.getCalendarByDate(today);
                if (!c.moveToFirst()) {
                    ContentValues values = new ContentValues();
                    values.put("date", today);
                    values.put("learn_count", 0);
                    values.put("review_count", 0);
                    values.put("is_signed", 0);
                    dbHelper.getWritableDatabase().insert("calendar", null, values);
                    c.close();
                    c = dbHelper.getCalendarByDate(today);
                    c.moveToFirst();
                }
                int oldLearn = c.getInt(c.getColumnIndexOrThrow("learn_count"));
                int oldReview = c.getInt(c.getColumnIndexOrThrow("review_count"));
                c.close();
                
                // 统计实际新学/复习的数量
                int learnAdd = 0;
                int reviewAdd = 0;
                if (isReviewMode) {
                    // 复习模式：统计本轮实际复习的单词数
                    reviewAdd = wordList.size(); // 本轮复习的单词数
                } else {
                    // 学习模式：统计本轮实际新学的单词数
                    learnAdd = wordList.size(); // 本轮学习的单词数
                }
                
                // 更新calendar表
                dbHelper.updateLearnReviewCount(today, oldLearn + learnAdd, oldReview + reviewAdd);
                finish(); // 返回主页面
            }
        }, 800);
    }
}